<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Draft;
use App\Models\DraftSection;
use Dingo\Api\Exception\StoreResourceFailedException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;
use DB;
use Exception;

class DraftController extends Controller
{
    /**
     * @SWG\Get(
     *     summary="草稿详情",
     *     path="/draft",
     *     description="用户草稿详情",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     *
     * @param Request $request
     *
     * @return array
     */
    public function index(Request $request)
    {
        $draft = Draft::where(['user_id' => $request->user()->id])->first();
        if (!$draft) {
            return ['data' => ''];
        }
        $draftSections = DraftSection::where(['play_id' => $draft->id])->first(['id', 'title', 'sequence', 'css', 'properties'])->toArray();
        foreach ($draftSections as &$section) {
            $section['css'] = json_decode($section['css']);
            $section['properties'] = json_decode($section['properties']);
        }

        $draft['sections'] = $draftSections;

        return ['data' => $draft];
    }

    /**
     * @SWG\Post(
     *     summary="创建或修改草稿",
     *     path="/draft",
     *     description="用户创建或修改草稿",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="授权令牌[Bearer <token>]",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="title",
     *         in="query",
     *         description="剧本标题",
     *         required=true,
     *         type="string"
     *     ),
     *     @SWG\Parameter(
     *         name="category_id",
     *         in="query",
     *         description="剧本分类",
     *         required=true,
     *         type="integer"
     *     ),
     *     @SWG\Parameter(
     *         name="page_turn_way",
     *         in="query",
     *         description="翻页方式(default:1)",
     *         required=false,
     *         type="integer",
     *         default=1
     *     ),
     *     @SWG\Parameter(
     *         name="is_cycle",
     *         in="query",
     *         description="循环播放(0-否[default],1-是)",
     *         required=false,
     *         type="integer",
     *         default=0
     *     ),
     *     @SWG\Parameter(
     *         name="is_auto",
     *         in="query",
     *         description="自动播放(0-否[default],1-是)",
     *         required=false,
     *         type="integer",
     *         default=0
     *     ),
     *     @SWG\Parameter(
     *         name="sections",
     *         in="query",
     *         description="章节数据(json格式):必要参数title[标题], sequence[顺序], css, properties",
     *         required=false,
     *         type="string"
     *     ),
     *     @SWG\Response(
     *         response=200,
     *         description=""
     *     )
     * )
     *
     * @param Request $request
     *
     * @return array;
     */
    public function store(Request $request)
    {
        $rules = [
            'title' => ['required', 'max:50'],
            'category_id' => ['required', 'exists:play_categories,id'],
            'page_turn_way' => ['required'],
            'is_cycle' => ['in:0,1'],
            'is_auto' => ['in:0,1'],
            'sections' => ['json'],
        ];
//        $payload = $request->only('title', 'description', 'category_id', 'page_turn_way', 'is_cycle', 'is_auto', 'is_template', 'is_share', 'sections');
        $messages = [
            'title.required' => '请填写标题',
            'category_id.required' => '请选择剧本类型',
            'category_id.exists' => '剧本类型异常',
            'page_turn_way.required' => '请选择翻页方式',
            'is_cycle.in' => '循环播放异常',
            'is_auto.in' => '自动播放异常',
            'is_template.in' => '自动播放异常',
            'sections.json' => '元件数据异常'
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            throw new StoreResourceFailedException('create or update error', $validator->errors());
        }

        DB::beginTransaction();
        try {
            $draft = Draft::firstOrNew(['user_id' => $request->user()->id]);

            $draft->user_id = $request->user()->id;
            $draft->title = $request->title;
            $draft->description = $request->description;
            $draft->category_id = $request->category_id;
            if (isset($request->page_turn_way)) {
                $draft->page_turn_way = $request->page_turn_way;
            }

            if (isset($request->is_cycle)) {
                $draft->is_cycle = $request->is_cycle;
            }
            if (isset($request->is_auto)) {
                $draft->is_auto = $request->is_auto;
            }
            if (isset($request->is_auto)) {
                $draft->is_auto = $request->is_auto;
            }
            if (isset($request->is_template)) {
                $draft->is_template = $request->is_template;
            }
            $draft->save();

            $sectionData = json_decode($request->sections);

            foreach ($sectionData as $data) {
                if (isset($data->id)) {
                    $draftSection = DraftSection::where(['id' => $data->id, 'draft_id' => $draft->id])->first();
                }
                if (!isset($draftSection) || !$draftSection) {
                    $draftSection = new DraftSection;
                }

                $draftSection->draft_id = $draft->id;
                $draftSection->title = $data->title;
                $draftSection->sequence = $data->sequence;
                $draftSection->css = json_encode($data->css);
                $draftSection->properties = json_encode($data->properties);

                $draftSection->save();
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollback();

            throw new StoreResourceFailedException('create or update error', $validator->errors());
        }

        return ['success' => true];
    }
}
